package com.reggie.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.acl.dataobject.Category;
import com.reggie.acl.mapper.CategoryMapper;
import com.reggie.common.enums.ResponseCode;
import com.reggie.common.exception.ReggieException;
import com.reggie.common.model.PageRequest;
import com.reggie.common.util.AssertUtils;
import com.reggie.service.service.CategoryService;
import com.reggie.service.service.DishService;
import com.reggie.service.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author yth
 * @since 2023-02-04
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    @Transactional
    public void removeById(long id) {
        // 判断是否有菜品属于此分类
        int dishCount = dishService.countByCategoryId(id);
        if (dishCount > 0) {
            throw new ReggieException(ResponseCode.CLIENT_ERROR,
                    "删除失败，有" + dishCount + "个菜品与当前分类关联");
        }
        // 判断是否有套餐属于此分类
        int setmealCount = setmealService.countByCategoryId(id);
        if (setmealCount > 0) {
            throw new ReggieException(ResponseCode.CLIENT_ERROR,
                    "删除失败，有" + setmealCount + "个套餐与当前分类关联");
        }
        // 正常删除
        if (categoryMapper.deleteById(id) <= 0) {
            log.error("数据库服务删除分类失败，id={}", id);
            throw new ReggieException(ResponseCode.SERVER_ERROR, "数据库服务删除分类失败");
        }
    }

    @Override
    public IPage<Category> page(PageRequest request) {
        AssertUtils.nonNull(request, ResponseCode.CLIENT_ERROR);
        AssertUtils.nonNull(request.getPage(), ResponseCode.CLIENT_ERROR);
        AssertUtils.nonNull(request.getPageSize(), ResponseCode.CLIENT_ERROR);

        LambdaQueryWrapper<Category> wrapper = Wrappers.lambdaQuery(Category.class)
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);

        return categoryMapper.selectPage(new Page<>(request.getPage(), request.getPageSize()), wrapper);
    }

    @Override
    public void save(Category category) {
        // 错误的数据提交
        String name = category.getName();
        if (StringUtils.isBlank(name)) {
            throw new ReggieException(ResponseCode.CLIENT_ERROR, "非法操作");
        }
        LambdaQueryWrapper<Category> wrapper = Wrappers
                .lambdaQuery(Category.class)
                .eq(Category::getName, name);
        int count = categoryMapper.selectCount(wrapper);
        if (count != 0) {
            throw new ReggieException(ResponseCode.CLIENT_ERROR, "尝试新增的分类的名称已存在，请换一个");
        }
        if (categoryMapper.insert(category) <= 0) {
            log.error("数据库服务添加分类失败，{}", category);
            throw new ReggieException(ResponseCode.SERVER_ERROR, "数据库服务添加分类失败");
        }
    }

    @Override
    public void updateById(Category category) {
        if (categoryMapper.updateById(category) <= 0) {
            log.error("数据库服务修改分类失败，{}", category);
            throw new ReggieException(ResponseCode.SERVER_ERROR, "数据库服务修改分类失败");
        }
    }

    @Override
    public List<Category> listByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper = Wrappers
                .lambdaQuery(Category.class)
                .eq(type != null, Category::getType, type);
        return categoryMapper.selectList(wrapper);
    }

    @Override
    public Optional<Category> getById(Long id) {
        return Optional.ofNullable(categoryMapper.selectById(id));
    }

    @Override
    public List<Category> getByIds(Collection<Long> ids) {
        return categoryMapper.selectBatchIds(ids);
    }
}
